package com.plexpt.chatgpt.controller;

import com.plexpt.chatgpt.ChatGPTStream;
import com.plexpt.chatgpt.ConsoleChatGPT;
import com.plexpt.chatgpt.entity.chat.Message;
import com.plexpt.chatgpt.listener.SseStreamListener;
import com.plexpt.chatgpt.util.Proxys;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.net.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName sse协议聊天 控制器
 * @Description TODO
 * @Author Jq
 * @Date 2023/5/10 12:05
 */
@RestController
public class SseController {


    private List<Message> beforeMessages = new FixSizeLinkedList<>(6);


    @GetMapping("/chat/sse")
    @CrossOrigin
    public SseEmitter sseEmitter(String systemPrompt,String prompt) {

        //国内需要代理 国外不需要
        Proxy proxy = Proxys.http("127.0.0.1", 9910);
        System.err.println("system------连接成功，开始回复本次消息：");
        System.out.println("\n system="+systemPrompt + "\n prompt=" + prompt);
        ChatGPTStream chatGPTStream = ChatGPTStream.builder()
                .timeout(600)
                .apiKey("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")
                .proxy(proxy)
                .apiHost("https://api.openai.com/")
                .build()
                .init();

        SseEmitter sseEmitter = new SseEmitter(-1L);
        System.out.println();
        SseStreamListener listener = new SseStreamListener(sseEmitter);
        Message systemMessage = Message.ofSystem(systemPrompt);
        Message message = Message.of(prompt);
        //记录本次消息
        beforeMessages.add(message);
        //封装 发送的消息
        List<Message> messages = new ArrayList<>();
        messages.add(systemMessage);
        messages.addAll(beforeMessages);



        listener.setOnComplate(msg -> {
            System.out.println("\n本次回复的内容：\n"+msg);
            //回答完成，可以做一些事情
            //记录本次回复
            beforeMessages.add(Message.ofAssistant(msg));
            sseEmitter.complete();
            System.err.println("\nsystem------本次消息回复结束");

        });


        chatGPTStream.streamChatCompletion(messages, listener);


        return sseEmitter;
    }

    class FixSizeLinkedList<T> extends LinkedList<T> {
        private static final long serialVersionUID = 3292612616231532364L;
        // 定义缓存的容量
        private int capacity;

        public FixSizeLinkedList(int capacity) {
            super();
            this.capacity = capacity;
        }

        @Override
        public boolean add(T e) {
            // 超过长度，移除最后一个
            if (size() + 1 > capacity) {
                super.removeFirst();
            }
            return super.add(e);
        }


    }
}
